package org.osami.gateway.jennic.mock;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Invalidate;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.ServiceProperty;
import org.apache.felix.ipojo.annotations.Validate;
import org.osami.gateway.jennic.IMessageHandler;
import org.osami.gateway.jennic.IMessageSource;

/**
 * Created by IntelliJ IDEA.
 * User: guillaume
 * Date: 17 juin 2010
 * Time: 14:23:21
 * To change this template use File | Settings | File Templates.
 */
@Component
@Provides(specifications = IMessageSource.class)
public class PseudoDataMessageSource implements IMessageSource, Runnable {

    @ServiceProperty(value = "data")
    private String type;

    private IMessageHandler handler;

    private boolean running = false;

    @Validate
    public void start() {
        System.out.println("Starting data message source");
        this.running = true;
        Thread thread = new Thread(this);
        thread.start();
    }

    @Invalidate
    public void stop() {
        System.out.println("Stopping data message source");
        this.running = false;
    }

    public void registerHandler(IMessageHandler handler) {
        this.handler = handler;
    }

    public void unregisterHandler(IMessageHandler handler) {
        this.handler = null;
    }

    public void run() {
        while (running) {
            try {
                Thread.sleep(5000l);
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }

            if (handler != null) {
                System.out.println("Sending data message at " + System.currentTimeMillis());
                handler.handle(new PseudoMessage(generateEventPayload()));
            }

        }
    }

    private String generateEventPayload() {
        return "O1Etest-node-id!Temp|26;Hydro|42;Light|120!";
    }
}
